package com.aloda.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.aloda.annotation.RateLimit;
import com.aloda.constant.ExceptionConstant;
import com.aloda.constant.PictureConstant;
import com.aloda.context.AdminBaseContext;
import com.aloda.context.UserBaseContext;
import com.aloda.dto.user.UserSafetyDTO;
import com.aloda.entity.Emp;
import com.aloda.entity.Picture;
import com.aloda.enums.UserCategory;
import com.aloda.exception.BaseException;
import com.aloda.manager.CosManager;
import com.aloda.mapper.EmpMapper;
import com.aloda.mapper.PictureMapper;
import com.aloda.properties.PicProperties;
import com.aloda.query.PicPageDTO;
import com.aloda.result.PageResult;
import com.aloda.service.PictureService;
import com.aloda.utils.ImageUtils;
import com.aloda.utils.LocalUploadUtils;
import com.aloda.vo.picture.PicPageVO;
import com.aloda.vo.picture.PicUploadVO;
import com.aloda.vo.picture.PictureExportVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author aloda
 * @description 针对表【picture】的数据库操作Service实现
 * @createDate 2024-12-18 12:59:24
 */
@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture> implements PictureService {

    @Resource
    private LocalUploadUtils localUploadUtils;

    @Resource
    private PictureMapper pictureMapper;

    @Resource
    private PicProperties picProperties;

    @Resource
    private EmpMapper empMapper;

    @Resource
    private CosManager cosManager;

    /**
     * 图片上传
     *
     * @param file
     * @return
     */
    @Override
    public PicUploadVO adminUpload(MultipartFile file) {
        // 获取总容量
        Long picResourceCapacity = picProperties.getPicResourceCapacity();
        // 获取当前占用容量
        List<Long> allPictureSize = pictureMapper.selectAllPictureSize();
        long sum = allPictureSize.stream().mapToLong(Long::longValue).sum();
        if (sum >= picResourceCapacity) {
            throw new BaseException(ExceptionConstant.RESOURCE_ERROR);
        }
        // 生成图片url
        String url;
        try {
            url = localUploadUtils.saveFile(file);
        } catch (IOException e) {
            throw new BaseException(ExceptionConstant.UPLOAD_ABNORMAL);
        }
        // 生成图片记录
        Picture picture = new Picture();
        picture.setUrl(url);
        picture.setPictureName(ImageUtils.getImageName(file));
        picture.setPictureSize(ImageUtils.getImageSize(file));
        picture.setPictureHeight(ImageUtils.getImageHeight(file));
        picture.setPictureWidth(ImageUtils.getImageWidth(file));
        picture.setPictureFormat(ImageUtils.getImageFormat(file));
        picture.setUseFlag(PictureConstant.IS_USE);
        Long currentId = AdminBaseContext.getCurrentId();
        Emp emp = empMapper.selectById(currentId);
        picture.setUserCategory(UserCategory.EMP);
        picture.setUserId(currentId);
        picture.setCreateUser(emp.getEmpAccount());
        picture.setCreateTime(LocalDateTime.now());
        // 保存图片记录
        pictureMapper.insert(picture);
        // 返回结果
        PicUploadVO picUploadVO = new PicUploadVO();
        picUploadVO.setUrl(url);
        return picUploadVO;
    }

    /**
     * 分页查询
     *
     * @param picPageDTO
     * @return
     */
    @Override
    public PageResult<PicPageVO> pageQuery(PicPageDTO picPageDTO) {
        Page<Picture> page = picPageDTO.toMpPageDefaultSortByCreateTimeDesc();
        LambdaQueryWrapper<Picture> pictureLambdaQueryWrapper = new LambdaQueryWrapper<>();
        pictureLambdaQueryWrapper
                .like(picPageDTO.getUrl() != null, Picture::getUrl, picPageDTO.getUrl())
                .like(picPageDTO.getCreateUser() != null, Picture::getCreateUser, picPageDTO.getCreateUser())
                .between(picPageDTO.getBeginTime() != null && picPageDTO.getEndTime() != null,
                        Picture::getCreateTime, picPageDTO.getBeginTime(), picPageDTO.getEndTime());
        pictureMapper.selectPage(page,pictureLambdaQueryWrapper);
        return PageResult.of(page, PicPageVO.class);
    }

    /**
     * 用户端头像图片上传
     *
     * @param file
     * @return
     */
    @Override
    @RateLimit(limit = 3, period = 30)
    public PicUploadVO userUpload(MultipartFile file) {
        // 获取总容量
        Long picResourceCapacity = picProperties.getPicResourceCapacity();
        // 获取当前占用容量
        List<Long> allPictureSize = pictureMapper.selectAllPictureSize();
        long sum = allPictureSize.stream().mapToLong(Long::longValue).sum();
        if (sum >= picResourceCapacity) {
            throw new BaseException(ExceptionConstant.RESOURCE_ERROR);
        }
        // 生成图片url
        String url;
        try {
            url = localUploadUtils.saveFile(file);
        } catch (IOException e) {
            throw new BaseException(ExceptionConstant.UPLOAD_ABNORMAL);
        }
        // 生成图片记录
        Picture picture = new Picture();
        picture.setUrl(url);
        picture.setPictureName(ImageUtils.getImageName(file));
        picture.setPictureSize(ImageUtils.getImageSize(file));
        picture.setPictureHeight(ImageUtils.getImageHeight(file));
        picture.setPictureWidth(ImageUtils.getImageWidth(file));
        picture.setPictureFormat(ImageUtils.getImageFormat(file));
        picture.setUseFlag(PictureConstant.IS_USE);
        UserSafetyDTO currentUser = UserBaseContext.getUser();
        picture.setUserCategory(UserCategory.USER);
        picture.setUserId(currentUser.getId());
        picture.setCreateUser(currentUser.getUserAccount());
        picture.setCreateTime(LocalDateTime.now());
        // 保存图片记录
        pictureMapper.insert(picture);
        // 返回结果
        PicUploadVO picUploadVO = new PicUploadVO();
        picUploadVO.setUrl(url);
        return picUploadVO;
    }

    /**
     * 导出图片信息到Excel
     * @param response HttpServletResponse
     * @param ids 图片ID列表
     */
    @Override
    public void exportPictureToExcel(HttpServletResponse response, List<Long> ids) {
        try {
            // 设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("图片信息表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 查询所有信息 如果ids为空查询所有信息，否则查询对应信息
            LambdaQueryWrapper<Picture> queryWrapper = new LambdaQueryWrapper<>();
            List<Picture> pictureList;
            if (ids.isEmpty()) {
                pictureList = pictureMapper.selectList(queryWrapper);
            } else {
                pictureList = pictureMapper.selectBatchIds(ids);
            }

            // 转换为导出VO
            List<PictureExportVO> exportVOList = pictureList.stream()
                    .map(picture -> {
                        PictureExportVO pictureExportVO = BeanUtil.copyProperties(picture, PictureExportVO.class);
                        pictureExportVO.setUserCategory(picture.getUserCategory().getDesc());
                        return pictureExportVO;
                    }).toList();

            // 使用EasyExcel导出
            EasyExcel.write(response.getOutputStream(), PictureExportVO.class)
                    .sheet("图片信息")
                    .doWrite(exportVOList);

        } catch (IOException e) {
            throw new RuntimeException(ExceptionConstant.EXPORT_EXCEL_ERROR, e);
        }
    }

    /**
     * 管理端图片上传 云版本
     *
     * @param file
     * @return
     */
    @Override
    public PicUploadVO adminCloudUpload(MultipartFile file) {
        // 获取总容量
        Long picResourceCapacity = picProperties.getPicResourceCapacity();
        // 获取当前占用容量
        List<Long> allPictureSize = pictureMapper.selectAllPictureSize();
        long sum = allPictureSize.stream().mapToLong(Long::longValue).sum();
        if (sum >= picResourceCapacity) {
            throw new BaseException(ExceptionConstant.RESOURCE_ERROR);
        }
        // 生成图片url
        String url;
        try {
            url = cosManager.upLoadFile(file);
        } catch (Exception e) {
            throw new BaseException(ExceptionConstant.UPLOAD_ABNORMAL);
        }
        // 生成图片记录
        Picture picture = new Picture();
        picture.setUrl(url);
        picture.setPictureName(ImageUtils.getImageName(file));
        picture.setPictureSize(ImageUtils.getImageSize(file));
        picture.setPictureHeight(ImageUtils.getImageHeight(file));
        picture.setPictureWidth(ImageUtils.getImageWidth(file));
        picture.setPictureFormat(ImageUtils.getImageFormat(file));
        picture.setUseFlag(PictureConstant.IS_USE);
        Long currentId = AdminBaseContext.getCurrentId();
        Emp emp = empMapper.selectById(currentId);
        picture.setUserCategory(UserCategory.EMP);
        picture.setUserId(currentId);
        picture.setCreateUser(emp.getEmpAccount());
        picture.setCreateTime(LocalDateTime.now());
        // 保存图片记录
        pictureMapper.insert(picture);
        // 返回结果
        PicUploadVO picUploadVO = new PicUploadVO();
        picUploadVO.setUrl(url);
        return picUploadVO;
    }

    /**
     * 用户端图片上传 云版本
     *
     * @param file
     * @return
     */
    @Override
    public PicUploadVO userCloudUpload(MultipartFile file) {
        // 获取总容量
        Long picResourceCapacity = picProperties.getPicResourceCapacity();
        // 获取当前占用容量
        List<Long> allPictureSize = pictureMapper.selectAllPictureSize();
        long sum = allPictureSize.stream().mapToLong(Long::longValue).sum();
        if (sum >= picResourceCapacity) {
            throw new BaseException(ExceptionConstant.RESOURCE_ERROR);
        }
        // 生成图片url
        String url;
        try {
            url = cosManager.upLoadFile(file);
        } catch (Exception e) {
            throw new BaseException(ExceptionConstant.UPLOAD_ABNORMAL);
        }
        // 生成图片记录
        Picture picture = new Picture();
        picture.setUrl(url);
        picture.setPictureName(ImageUtils.getImageName(file));
        picture.setPictureSize(ImageUtils.getImageSize(file));
        picture.setPictureHeight(ImageUtils.getImageHeight(file));
        picture.setPictureWidth(ImageUtils.getImageWidth(file));
        picture.setPictureFormat(ImageUtils.getImageFormat(file));
        picture.setUseFlag(PictureConstant.IS_USE);
        UserSafetyDTO currentUser = UserBaseContext.getUser();
        picture.setUserCategory(UserCategory.USER);
        picture.setUserId(currentUser.getId());
        picture.setCreateUser(currentUser.getUserAccount());
        picture.setCreateTime(LocalDateTime.now());
        // 保存图片记录
        pictureMapper.insert(picture);
        // 返回结果
        PicUploadVO picUploadVO = new PicUploadVO();
        picUploadVO.setUrl(url);
        return picUploadVO;
    }
}




